package com.tpsix.annotation;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.tpsix.enums.SensitiveTypeEnum;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Objects;

/**
 * jackson序列化拦截
 */
@NoArgsConstructor
public class SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveTypeEnum sensitiveTypeEnum;

    public SensitiveSerialize(SensitiveTypeEnum sensitiveTypeEnum) {
        this.sensitiveTypeEnum = sensitiveTypeEnum;
    }

    @Override
    public void serialize(String value, JsonGenerator generator, SerializerProvider serializers) throws IOException {

        String val = sensitiveTypeEnum.encode(value);
        generator.writeString(val);

    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (Objects.nonNull(property)) {
            if (Objects.equals(property.getType().getRawClass(), String.class)) {
                Desensitization desensitization = property.getAnnotation(Desensitization.class);
                if (Objects.isNull(desensitization)) {
                    desensitization = property.getContextAnnotation(Desensitization.class);
                }
                if (Objects.nonNull(desensitization)) {
                    return new SensitiveSerialize(desensitization.value());
                }
            }
            return prov.findValueSerializer(property.getType(), property);
        }
        return prov.findNullValueSerializer(null);
    }

}
